package com.luobr.backend.manage;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.luobr.backend.config.OssClientConfig;
import com.luobr.backend.model.dto.image.ImageInfoResult;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author: 罗念笙
 * @date: 2025/2/24 15:52
 * 操作 OSS 对象存储器的客户端
 */
@Component
public class OssManager {

    @Resource
    private OssClientConfig ossClientConfig;
    @Resource
    private OSS ossClient;

    /**
     * 上传对象
     *
     * @param key  唯一键，上传图片的相对路径 例如：test/Al_tair.png
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossClientConfig.getBucketName(), key, file);
        return ossClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     *
     * @param key 唯一键，上传图片的相对路径 例如：test/Al_tair.png
     */
    public OSSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(ossClientConfig.getBucketName(), key);
        return ossClient.getObject(getObjectRequest);
    }

    /**
     * 上传图片（附带图片信息）
     *
     * @param key 唯一键，上传图片的相对路径 例如：test/Al_tair.png
     */
    public ImageInfoResult getImageObject(String key) {
        // 获取图片信息的封装对象
        GetObjectRequest getObjectRequest = new GetObjectRequest(ossClientConfig.getBucketName(), key);
        // 获取图片信息
        String style = "image/info";
        // 构造处理参数
        getObjectRequest.setProcess(style);
        // 获取图像对象信息
        OSSObject object = ossClient.getObject(getObjectRequest);
        String jsonStr = IoUtil.readUtf8(object.getObjectContent());
        // 解析JSON
        JSONObject info = new JSONObject(jsonStr);
        // 返回封装的图片信息
        Long imgSize = info.getJSONObject("FileSize").getLong("value");
        String imgFormat = info.getJSONObject("Format").getStr("value");
        Long frameCount = info.getJSONObject("FrameCount").getLong("value");
        Integer imgHeight = info.getJSONObject("ImageHeight").getInt("value");
        Integer imgWidth = info.getJSONObject("ImageWidth").getInt("value");
        return new ImageInfoResult(imgSize, imgFormat, frameCount, imgHeight, imgWidth);
    }
}